
export let timestampFormat = (timestamp, format) => {
  let result = ''
  let zeroFill = val => val < 10 ? '0' + val : val

  timestamp = parseInt(timestamp) * 1000
  format = format || 'YYYY-MM-DD hh:mm:ss'

  if (!timestamp) {
    result = '-'
  } else {
    let sFormat = format
    format = format.split(' ')
    let dateFormat = format[0]
    let timeFormat = format[format.length - 1]
    let dateSymbol = dateFormat.match(/[^Y,^M,^D]/)[0]
    let timeSymbol = timeFormat.match(/[^h,^m,^s]/)[0]
    let clearance = sFormat.replace(dateFormat, '').replace(timeFormat, '')
    let datetime = new Date(timestamp)
    let year = datetime.getFullYear()
    let month = zeroFill(datetime.getMonth() + 1)
    let day = zeroFill(datetime.getDate())
    let hours = zeroFill(datetime.getHours())
    let minute = zeroFill(datetime.getMinutes())
    let second = zeroFill(datetime.getSeconds())
    if (dateFormat.match(/Y/)) {
      result += year
    }
    if (dateFormat.match(/M/)) {
      result += dateSymbol + month
    }
    if (dateFormat.match(/D/)) {
      result += dateSymbol + day
    }
    if (timeFormat.match(/h/)) {
      result += clearance + hours
    }
    if (timeFormat.match(/m/)) {
      result += timeSymbol + minute
    }
    if (timeFormat.match(/s/)) {
      result += timeSymbol + second
    }
  }

  return result.replace(/^[^\d]+/, '')
}

/**
 * 价格过滤器，/100 && 保留两位小数
 */
export let priceFilter = (price) => {
  return (price / 100).toFixed(2)
}

export let currency = (value, prefix = '$', type) => {
  let money = (value / 100).toFixed(2)
  if (type === 2) {
    money = money.replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
  }
  return prefix + money
}

export let priceFloat = (value, prefix = '$') => {
  return prefix + parseFloat((value / 100))
}

/**
 * 订单类型
 */
export let orderStatusFilter = (value) => {
  let orderStatus = {
    1: '未付款',
    2: '部分付款',
    3: '支付中',
    4: '已付款',
    5: '交易完成',
    6: '订单已取消',
    7: '订单已关闭'
  }
  return orderStatus[value]
}

/*
 *格式化手机号码
 */
export let codeFilter = (val) => {
  if (val) {
    let str = ''
    for (let i = 0, len = val.length; i < len; i++) {
      str += val[i]
      if ((i + 1) % 4 === 0) {
        str += ' '
      }
    }
    return str
  }
}

/**
 * fmt 格式 'yyyy-MM-dd' 'yyyy-MM-dd HH:mm:ss'
 *时间格式化
 */
export let timeFormat = (val, fmt) => {
  let data = new Date(val * 1000)
  let o = {
    'M+': data.getMonth() + 1, // 月份
    'd+': data.getDate(), // 日
    'h+': data.getHours(), // 小时
    'm+': data.getMinutes(), // 分
    's+': data.getSeconds(), // 秒
    'q+': Math.floor((data.getMonth() + 3) / 3), // 季度
    'S': data.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (data.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}
